package com.xtwy.security;

import com.xtwy.dao.UserDao;
import com.xtwy.domain.Role;
import com.xtwy.domain.User;
import lombok.extern.java.Log;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @作 者: 侯建军
 * @日 期: 2018/7/29 22:22
 * @描 述:
 * @公 司：山西迅腾伟业
 */
@Log
@Service
public class CustomUserService implements UserDetailsService {
    //自定义UserDetailsService 接口
    @Autowired
    UserDao userDao;
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(CustomUserService.class);
    @Override
    public UserDetails loadUserByUsername(String username) {
        log.warning(username);
        // /重写loadUserByUsername 方法获得 userdetails 类型用户
        User user = userDao.findByUserName(username);
        if(user == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        //用于添加用户的权限,将用户权限添加到authorities
        for(Role role:user.getRoles())
        {
            log.warning(role.getValue()+"---------------------");
            authorities.add(new SimpleGrantedAuthority(role.getValue()));
            logger.info("loadUserByUsername: " + user);
        }
        user.setGrantedAuthorities(authorities);
        //用于登录时 @AuthenticationPrincipal 标签取值
        return user;
    }
}
